'use strict';
const  path =  require('path');
const  fs =  require('fs');
const util = require('../util/util') 
const Controller = require('./base');
const awaitWriteStream = require('await-stream-ready').write
const sendToWormhole = require('stream-wormhole')

/**
 * @controller History
 */
 class UserHistoryController extends Controller { 

  async list() {  // 以次为案例 扩展为模糊分页查询
    this.check(); 
    const { ctx ,app} = this;  
    let id = this.ctx.state.user.data.id
    const results = await app.mysql.select('history',{
      where: { uid: id },
      orders: [['created_at','desc'], ['id','desc']],
      limit: 10,
      offset: 0
    });
    console.log("results")
    console.log(results)
    this.success(results) 
  }

  async search() {  // 模糊分页查询
   
    const { ctx ,app} = this;  
    let { sid,page,pageSize,type } = this.args()
    let id = this.ctx.state.user.data.id 
    page = page || 1; pageSize = pageSize ? pageSize || 10;
    var   offset = (page - 1) * pageSize
    
    let sql = `select count (*) from  history where uid = ${id} `
    if(sid)  sql +=` and sid = ${sid} `;
    if(type) sql +=` and type = ${type} `;
    sql +=` limit ${offset} , ${pageSize} `

    let results= await this.app.mysql.query(sql);
   

    console.log("results")
    console.log(results)
    this.success(results) 
  }
 
  async history() {  
    console.log("history",this.formatDate())
    let uid = this.ctx.state.user.data.id 
    let { sid } = this.args()
    if(!sid)  return  this.error("需要sid参数") 
    const record = await this.app.mysql.get('history', { uid, sid, }); 
    console.log(record)
    if(record)  return  this.success(record) // this.error('已收藏过')  
    let data = await this.app.mysql.insert('history',{ uid, sid, created_at:this.formatDate(), }) 
    this.success(data)

 }
  
}
module.exports =  UserHistoryController
 
 
